# -*- coding: UTF-8 -*-
# @Time : 2022/1/5 0005 9:12
# @Author : lyw
# @Remark : 烟感
import time

from db.common.IOTManager.GasDetector.gas_detector import GASDeviceSelectDB, GASDeviceListDB, GASDeviceRetrieveDB
from model.common.IOTManager.iot_base import SRoomIOTMiddleModel
from server.public.IOTManager.server_base import IOTBaseServer

try:
    from opm_pyirm import GetStatusById
except ImportError:
    try:
        from bsmiddle import GetStatusById
    except ImportError:
        def GetStatusById(*args):
            return 1, 2

from utils.classes.custom_exception import VerifyError
from index import _


class GASDeviceSelectServer(IOTBaseServer):
    __db__ = GASDeviceSelectDB
    __model__ = SRoomIOTMiddleModel

    def device_info(self, device_list, state_dict: dict = None):
        """
        获取设备信息
        @param state_dict:
        @param device_list:
        @return:
        """
        if state_dict is None:
            state_dict = {"state": 1}
        res_device_data = []
        if state_dict["state"] != 2:
            state_dict["state"] = 1
        for device_data in device_list:
            status = GetStatusById(device_data["code"])
            if isinstance(status ,int):
                status = status
            else:
                status = status[1]
            if state_dict is not None:
                if status != 1:
                    state_dict["state"] = 2
            res_device_data.append(
                {"name": device_data["mxlabel"], "code": device_data["code"],
                 "mxdevicetype": device_data["mxdevicetype"],
                 "state": self.set_state(status), "local": self.db.get_local(
                             self.model(device_type=self.db.device_type, iot_code=device_data["code"],
                                        sroom_code=""))})

        return res_device_data


class GASDeviceListServer(GASDeviceSelectServer):
    __db__ = GASDeviceListDB

    def select(self, **kwargs):
        query_dev_list = self.db.query_device()

        for dev_data in query_dev_list:
            status = GetStatusById(dev_data["code"])[1]
            dev_data["state"] = self.set_state(status)

        return query_dev_list


class GASDeviceRetrieveServer(GASDeviceListServer):
    __db__ = GASDeviceRetrieveDB

    def select(self, **kwargs):
        res_data_list = []
        dev_tmp = self.db.read_template()
        # 时间处理
        start_time, end_time = self.process_time(**kwargs)
        # 定义要取的参数
        dev_tmp_dict = {}
        query_dev_list = self.db.select_sub_monitor(kwargs["code"])
        if query_dev_list:
            if not dev_tmp.get(query_dev_list[0]["mxpluginname"]):
                raise VerifyError(_("设备模板获取失败"))
            dev_tmp_dict = dev_tmp[query_dev_list[0]["mxpluginname"]]
            # 查询数据
            self.query_monitor_data(query_dev_list[0]["code"], start_time, end_time, dev_tmp_dict, res_data_list.append,
                                    kwargs)

        head = [{"key": "date_time", "name": "监测时间"},
                {"key": "state", "name": "状态"},
                {"key": "value", "name": dev_tmp_dict.get("mxlabel", "")},
                {"key": "desc", "name": "备注"}]

        return {"head": head, "data": res_data_list, "total": len(res_data_list)}

    def query_monitor_data(self, monitor_key, start_time, end_time, head_dict, res_app, kwargs):
        """
        查询数据库数据
        @param res_app:
        @param kwargs:
        @param head_dict:
        @param monitor_key:
        @param start_time:
        @param end_time:
        @return:
        """
        state_dict = {"0": (0, 2, 3, 4, 5), "1": (1,)}
        monitor_table_data = self.db.query_table_data(code=monitor_key, count=100,
                                                      start_time=int(start_time.timestamp()),
                                                      end_time=int(end_time.timestamp())
                                                      )
        for monitor_data in monitor_table_data:
            # 遍历所有的table 表
            if state_dict.get(kwargs.get("state"), ""):
                if monitor_data["State"] in state_dict[kwargs["state"]]:
                    continue

            res_app(
                {"date_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(monitor_data["_CREATETIME_"])),
                 "state": self.set_state(monitor_data["State"]),
                 "value": monitor_data[head_dict["key"]],
                 "desc": ""
                 })
